"use strict";

import axios from "axios";
import { ApiURL, comApiUrl } from "@/components/BimIntegrate/websiteConfig.js";
import { Message } from "ant-design-vue";
import { getToken } from "./index.js";
import { modelConfig } from "@/components/BimIntegrate/websiteConfig.js";
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config = {
  baseURL: ApiURL,
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  timeout: 60 * 1000 * 5, // Timeout
  withCredentials: false, // Check cross-site Access-Control
};

const _axios = axios.create(config);
export const _pureAxios = axios.create({...config})

// 该实例未设置响应守卫拦截
_pureAxios.interceptors.request.use(
  async function(config) {
    if (config.urlType === "common") {
      config.baseURL = comApiUrl;
    }
    config.headers.common["x-access-token"] = sessionStorage.getItem("bimToken")
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

_axios.interceptors.request.use(
  function(config) {
    if (config.urlType === "common") {
      config.baseURL = comApiUrl;
    }
    config.headers.common["x-access-token"] = sessionStorage.getItem("bimToken");
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    console.log(response)
    const res = response.data;
    let tokenPromise = null
    if(res.code === 56 && response.config.url !== '/token') {
      tokenPromise = validateToken()
    } else
    if (res.code !== 0 && response.config && !response.config.unValidateCode) {
        Message.error({
          content: '网络异常，请稍后再试'
        });
      return Promise.reject(new Error(res.message || "Error"));
    }
    return new Promise((resolve, reject) => { // 如果token无效，那么就获取新的token,在新token返回之后，重新发起之前的请求
      if(tokenPromise) {
        tokenPromise.then(() => {
          const { url, method, params, data, urlType } = response.config
          _axios({
            url,
            method,
            data,
            params,
            urlType
          }).then((repeatRes) => {
            resolve(repeatRes)
          }).catch((e) => {
            reject(e)
          })
        }).catch((e) => {
          reject(e)
        })
      } else {
        resolve(res)
      }
    });
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

// 验证token
export async function validateToken() {
  const params = {
    appKey: modelConfig.appKey,
    appSecret: modelConfig.appSecret
  };
  const [err, res] = await getToken(params);
  if (!err) {
    sessionStorage.setItem("bimToken", res.data.token);
    return Promise.resolve(res)
  }
  return Promise.reject(err)
}
export default _axios;
